# -*- coding:utf-8 -*-
import json

from app import db
from app.tools.log import log
from app.tools.redis_op import Operator

op = Operator()
name_dict = dict(
    brand=u'品牌',
    price=u'价格范围',
    car_model=u'车型',
    car_age=u'车龄',
    mileage=u'里程',
    gearbox=u'变速箱类型',
    exhaust=u'排量范围',
    seat=u'座位数',
    standard=u'排放标准',
    color=u'颜色',
)


class ModelMixin(object):
    @classmethod
    def new(cls, form):
        m = cls(form)
        m.save()
        return m

    @classmethod
    def update(cls, model_id, form):
        m = cls.query.get(model_id)
        m._update(form)
        m.save()

    @classmethod
    def delete(cls, model_id):
        m = cls.query.get(model_id)
        m.remove()

    def __repr__(self):
        class_name = self.__class__.__name__
        return u'<{0}: \n  {1}\n>'.format(class_name, self.id)

    def save(self):
        db.session.add(self)
        db.session.commit()

    def remove(self):
        db.session.delete(self)
        db.session.commit()

    @classmethod
    def __sort(cls, li):
        for model_id in li:
            m = cls.query.get(model_id)
            m.sort = str(li.index(model_id))
            m.save()


class Carousel(db.Model, ModelMixin):  # 轮播图
    __tablename__ = 'carousels'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.Text())
    path = db.Column(db.Text())
    sort = db.Column(db.Integer, index=True)

    def change_url(self, url):
        self.url = url

    def change_path(self, path):
        self.path = path


class Carousel_APP(db.Model, ModelMixin):  # 轮播图手机端
    __tablename__ = 'carousels_app'
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.Text())
    path = db.Column(db.Text())
    sort = db.Column(db.Integer, index=True)

    def change_url(self, url):
        self.url = url

    def change_path(self, path):
        self.path = path


class Navigation(db.Model, ModelMixin):  # 导航栏
    __tablename__ = 'navigations'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.Text())
    url = db.Column(db.Text())

    # @staticmethod
    # def init():
    #     NAV = [
    #         u'首页',
    #         u'买车',
    #         u'卖车',
    #         u'租赁',
    #         u'金融',
    #         u'服务',
    #     ]
    #     for i in NAV:
    #         form = dict(
    #             name=i,
    #             url=''
    #         )
    #         n = Navigation(form)
    #         n.save()

    def __init__(self, form):
        self.name = form.get('name', '')
        self.url = form.get('url', '')

    def _update(self, form):
        self.name = form.get('name', '')
        self.url = form.get('url', '')


class AttrBrand(db.Model, ModelMixin):  # 车辆属性的品牌
    __tablename__ = 'attr_brands'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20))  # 品牌名字
    ename = db.Column(db.String(20))  # 名字的拼音
    first_ename = db.Column(db.String(20))  # 名字的拼音首字母
    sort = db.Column(db.Integer)  # 排序


class AttrCarModel(db.Model, ModelMixin):  # 车辆属性的车型
    __tablename__ = 'attr_car_models'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(24))
    sort = db.Column(db.Integer)  # 排序

    def _update(self, form):
        pass


class HotCity(db.Model, ModelMixin):  # 热门城市
    __tablename__ = 'hotCitys'
    id = db.Column(db.Integer, primary_key=True)
    city = db.Column(db.String(64))

    def __init__(self, form):
        self.city = form.get('city', '')


class BusinessScope(db.Model, ModelMixin):  # 业务范围城市
    __tablename__ = 'business_scope'
    id = db.Column(db.Integer, primary_key=True)
    city = db.Column(db.String(64))


class LinkSite(db.Model, ModelMixin):  # 友情链接
    __tablename__ = 'linkSites'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(20))
    url = db.Column(db.Text())
    state = db.Column(db.Boolean, default=True)  # 显示/隐藏
    sort = db.Column(db.Integer)

    def __init__(self, form):
        self.name = form.get('name', '')
        self.url = form.get('url', '')
        self.state = form.get('state', '')

    def _update(self, form):
        self.name = form.get('name', '')
        self.url = form.get('url', '')
        self.state = form.get('state', '')


class Third_Party_Code(db.Model, ModelMixin):  # 第三方代码
    __tablename__ = 'third_party_code'
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.Text)


class CarAttribute(object):  # redis车辆属性数据模型
    """
    key    field          value
    color     1  (id)   "(红色, 1)"  (value, sort)
    """

    @staticmethod
    def init():
        Models = [AttrBrand, AttrCarModel]
        for model in Models:
            ms = model.query.all()
            for m in ms:
                m.remove()
        ATTR = ('brand', 'car_type', 'price', 'car_age',
                'mileage', 'gearbox', 'exhaust', 'seat',
                'standard', 'color', 'range_rel', 'color_values')
        for key in ATTR:
            op.r.delete(key)


def delete_data():
    CarAttribute.init()  # 删除车辆属性所有数据


def insert_data():  # 插入车辆属性数据，测试用。
    delete_data()
    from ..views.siteSetting import CarAttr

    # 品牌
    from pypinyin import lazy_pinyin
    b = {}
    brands = CarAttr.brand['brand']
    for name in brands:
        data = dict(
            name=name,
            ename=''.join(lazy_pinyin(name)),
            first_ename=''.join(i[0] for i in lazy_pinyin(name)),
            sort=str(brands.index(name) + 1)
        )
        a = AttrBrand(**data)
        a.save()
        b[a.id] = (a.name, a.sort)
    op.hsetall('brand', b)

    # 车型
    type = {}
    cs = CarAttr.car_model['car_model']
    for name in cs:
        data = dict(
            name=name,
            sort=str(cs.index(name) + 1)
        )
        a = AttrCarModel(**data)
        a.save()
        type[a.id] = (a.name, a.sort)
    op.hsetall('car_type', type)

    range_field = ('price', 'car_age', 'mileage', 'exhaust')
    other = ('gearbox', 'standard', 'seat', 'color')
    all = other + range_field
    for key in all:
        f = getattr(CarAttr, key)
        v = f.get(key)
        for item in v:
            id = str(v.index(item) + 1)
            op.hset(key, id, (item, id))
    # 范围
    range_rel = CarAttr.range_rel
    for k, range in range_rel.items():
        for key in range_field:
            f = getattr(CarAttr, key)
            r = f.get(key)
            for item in r:
                if k == item:
                    id = str(r.index(item) + 1)
                    op.hset('range_rel', key + id, range)
                    break

    # 颜色
    color_values = CarAttr.color_values
    for color_value in color_values:
        index = str(color_values.index(color_value) + 1)
        op.hset('color_values', index, color_value)


if __name__ == '__main__':
    from app.views.siteSetting import CarAttr
    from app.models.site_setting import insert_data
    import redis

    r = redis.Redis('localhost', 6379)

